import base64
import json
import hmac
import hashlib


class Convert(object):
    # def __init__(self):
    #     pass

    # hmac加密
    def convertHmac(self, HmacStr):
        hValue = b"%s" % HmacStr
        h = hmac.new(b"ios", hValue, hashlib.sha256)
        return h.hexdigest()

    # md5加密
    def convertMD5(sel, Md5Str):
        # 创建md5对象
        m = hashlib.md5()
        # 此处必须encode
        # 若写法为m.update(str)  报错为： Unicode-objects must be encoded before hashing
        # 因为python3里默认的str是unicode
        # 或者 b = bytes(str, encoding='utf-8')，作用相同，都是encode为bytes
        m.update(Md5Str.encode(encoding='utf-8'))
        return m.hexdigest()

    # base64加密
    def convertBase64(self, data):
        encode = base64.b64encode(json.dumps(data).encode('utf-8'))
        return str(encode, 'utf-8')

    # base64加密+md5
    def convertBase64Md5(self, data):
        base64Str = base64.b64encode(json.dumps(data).encode('utf-8'))
        Base64Md5Str = hashlib.md5(base64Str.encode('utf-8')).hexdigest()
        return Base64Md5Str

